import strJobApplicationPageHtml from "./JobApplicationPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { jobApplicationService } from "../../services/jobApplicationService";

export class JobApplicationPage {
  constructor() {
    this.currentPage = 1;
    this.pageSize = 10;
    this.searchKeyword = "";
    this.searchType = "id";
    this.totalPages = 0;
    this.totalItems = 0;
    this.selectedApplications = new Set();
  }

  render() {
    const dom = DomUtils.convertToDom(strJobApplicationPageHtml);
    this._bindElements(dom);
    this._bindEvents(dom);
    this._loadData();
    return dom;
  }

  _bindElements(dom) {
    this.searchTypeSelect = dom.querySelector("#searchType");
    this.searchInput = dom.querySelector("#searchInput");
    this.searchBtn = dom.querySelector("#searchBtn");
    this.batchDeleteBtn = dom.querySelector("#batchDeleteBtn");
    this.selectAllCheckbox = dom.querySelector("#selectAll");
    this.applicationTableBody = dom.querySelector("#applicationTableBody");
    this.pagination = dom.querySelector("#pagination");
    this.statusModal = dom.querySelector("#statusModal");
    this.statusForm = dom.querySelector("#statusForm");
    this.modalClose = dom.querySelector("#modalClose");
    this.applicationId = dom.querySelector("#applicationId");
    this.statusSelect = dom.querySelector("#status");
    this.detailModal = dom.querySelector("#detailModal");
    this.detailModalClose = dom.querySelector("#detailModal .close");
    this.statusModalFooterClose = dom.querySelector(
      "#statusModal .btn-secondary"
    );
    this.detailModalFooterClose = dom.querySelector(
      "#detailModal .btn-secondary"
    );

    // Initialize Bootstrap modals
    this.statusModalInstance = new bootstrap.Modal(this.statusModal);
    this.detailModalInstance = new bootstrap.Modal(this.detailModal);
  }

  async _loadData() {
    try {
      const params = {
        page: this.currentPage,
        pageSize: this.pageSize,
      };

      const result = await jobApplicationService.getJobApplications(params);
      this._renderTable(result.items);

      this.totalPages = result.totalPages;
      this.totalItems = result.total;
      this._renderPagination();
      this._showPagination();

      this._resetBatchDeleteButton();
    } catch (error) {
      console.error("Error loading job applications:", error);
      this._showError("加载投简信息失败：" + error.message);
    }
  }

  _renderTable(applications) {
    this.applicationTableBody.innerHTML = applications
      .map(
        (application) => `
          <tr>
            <td>
              <div class="custom-checkbox custom-control">
                <input type="checkbox" class="custom-control-input application-checkbox" id="application-${
                  application.id
                }" data-id="${application.id}">
                <label for="application-${
                  application.id
                }" class="custom-control-label"></label>
              </div>
            </td>
            <td>${application.id}</td>
            <td>${application.companyName || "-"}</td>
            <td>${application.jobTitle || "-"}</td>
            <td>${application.jobType || "-"}</td>
            <td>${application.seekerName || "-"}</td>
            <td>${application.seekerEmail || "-"}</td>
            <td>${application.applicationDate || "-"}</td>
            <td>${application.applicationStatus || "-"}</td>
            <td>
              <button class="btn btn-info btn-sm detail-btn" data-id="${
                application.id
              }">
                <i class="fas fa-eye"></i> 详情
              </button>
              <button class="btn btn-primary btn-sm status-btn" data-id="${
                application.id
              }">
                <i class="fas fa-edit"></i> 更新状态
              </button>
              <button class="btn btn-danger btn-sm delete-btn" data-id="${
                application.id
              }">
                <i class="fas fa-trash"></i> 删除
              </button>
            </td>
          </tr>
        `
      )
      .join("");
  }

  _renderPagination() {
    let startPage = Math.max(1, this.currentPage - 2);
    let endPage = Math.min(this.totalPages, startPage + 4);

    if (endPage - startPage < 4) {
      startPage = Math.max(1, endPage - 4);
    }

    let pages = [];

    pages.push(`
      <li class="page-item ${this.currentPage === 1 ? "disabled" : ""}">
        <a class="page-link" href="#" data-page="1" title="首页">
          <i class="fas fa-angle-double-left"></i>
        </a>
      </li>
    `);

    pages.push(`
      <li class="page-item ${this.currentPage === 1 ? "disabled" : ""}">
        <a class="page-link" href="#" data-page="${
          this.currentPage - 1
        }" title="上一页">
          <i class="fas fa-angle-left"></i>
        </a>
      </li>
    `);

    for (let i = startPage; i <= endPage; i++) {
      pages.push(`
        <li class="page-item ${i === this.currentPage ? "active" : ""}">
          <a class="page-link" href="#" data-page="${i}">${i}</a>
        </li>
      `);
    }

    pages.push(`
      <li class="page-item ${
        this.currentPage === this.totalPages ? "disabled" : ""
      }">
        <a class="page-link" href="#" data-page="${
          this.currentPage + 1
        }" title="下一页">
          <i class="fas fa-angle-right"></i>
        </a>
      </li>
    `);

    pages.push(`
      <li class="page-item ${
        this.currentPage === this.totalPages ? "disabled" : ""
      }">
        <a class="page-link" href="#" data-page="${
          this.totalPages
        }" title="末页">
          <i class="fas fa-angle-double-right"></i>
        </a>
      </li>
    `);

    this.pagination.innerHTML = pages.join("");
  }

  _bindEvents(dom) {
    // 搜索按钮点击事件
    this.searchBtn?.addEventListener("click", async () => {
      const searchValue = this.searchInput.value.trim();
      const searchType = this.searchTypeSelect.value;

      if (!searchValue) {
        this._showError("请输入搜索内容");
        return;
      }

      try {
        let applications;
        if (searchType === "id") {
          const id = parseInt(searchValue);
          if (isNaN(id)) {
            this._showError("请输入有效的投简ID");
            return;
          }
          const application = await jobApplicationService.getJobApplication(id);
          applications = application ? [application] : [];
        } else {
          // 获取所有投简信息并在前端进行模糊匹配
          const allApplications =
            await jobApplicationService.getJobApplications(1, 1000);
          applications = allApplications.items.filter((application) => {
            const searchText = searchValue.toLowerCase();
            if (searchType === "companyName") {
              return (application.companyName || "")
                .toLowerCase()
                .includes(searchText);
            } else if (searchType === "jobTitle") {
              return (application.jobTitle || "")
                .toLowerCase()
                .includes(searchText);
            } else if (searchType === "seekerName") {
              return (application.seekerName || "")
                .toLowerCase()
                .includes(searchText);
            } else if (searchType === "seekerEmail") {
              return (application.seekerEmail || "")
                .toLowerCase()
                .includes(searchText);
            } else if (searchType === "status") {
              return (application.applicationStatus || "")
                .toLowerCase()
                .includes(searchText);
            }
            return false;
          });
        }

        if (applications.length > 0) {
          this._renderTable(applications);
          this._hidePagination();
          this._addBackButton();
        } else {
          this._showError(
            `未找到${
              searchType === "id"
                ? "投简ID"
                : searchType === "companyName"
                ? "企业名称"
                : searchType === "jobTitle"
                ? "岗位名称"
                : searchType === "seekerName"
                ? "求职者姓名"
                : searchType === "seekerEmail"
                ? "求职者邮箱"
                : "投简状态"
            }包含 "${searchValue}" 的投简信息`
          );
        }
      } catch (error) {
        console.error("Error searching job applications:", error);
        this._showError("查询失败：" + error.message);
      }
    });

    // 搜索输入框回车事件
    this.searchInput?.addEventListener("keypress", (e) => {
      if (e.key === "Enter") this.searchBtn.click();
    });

    // 分页点击
    this.pagination?.addEventListener("click", (e) => {
      e.preventDefault();
      if (e.target.tagName === "A") {
        this.currentPage = parseInt(e.target.dataset.page);
        this._loadData();
      }
    });

    // 表格操作
    this.applicationTableBody?.addEventListener("click", async (e) => {
      const btn = e.target.closest("button");
      if (!btn) return;

      const id = btn.dataset.id;
      if (!id) return;

      if (btn.classList.contains("status-btn")) {
        await this._showStatusModal(id);
      } else if (btn.classList.contains("detail-btn")) {
        await this._showDetailModal(id);
      } else if (btn.classList.contains("delete-btn")) {
        if (confirm("确定要删除这条投简信息吗？")) {
          try {
            await jobApplicationService.deleteJobApplication(id);
            this._loadData();
          } catch (error) {
            console.error("Error deleting job application:", error);
            alert("删除投简信息失败：" + error.message);
          }
        }
      }
    });

    // 全选/取消全选
    this.selectAllCheckbox?.addEventListener("change", (e) => {
      const checkboxes = dom.querySelectorAll(".application-checkbox");
      checkboxes.forEach((checkbox) => {
        checkbox.checked = e.target.checked;
      });
      this._updateBatchDeleteButton();
    });

    // 单个复选框变化时更新批量删除按钮状态
    this.applicationTableBody?.addEventListener("change", (e) => {
      if (e.target.classList.contains("application-checkbox")) {
        this._updateBatchDeleteButton();
      }
    });

    // 批量删除按钮点击事件
    this.batchDeleteBtn?.addEventListener("click", async () => {
      const selectedIds = Array.from(
        dom.querySelectorAll(".application-checkbox:checked")
      ).map((checkbox) => parseInt(checkbox.dataset.id));

      if (selectedIds.length === 0) {
        alert("请选择要删除的投简信息");
        return;
      }

      if (!confirm(`确定要删除选中的 ${selectedIds.length} 个投简信息吗？`)) {
        return;
      }

      try {
        await jobApplicationService.batchDeleteJobApplications(selectedIds);
        this._loadData();
        alert("批量删除成功");
      } catch (error) {
        console.error("Error batch deleting applications:", error);
        alert("批量删除失败：" + error.message);
      }
    });

    // 状态模态框关闭按钮事件
    this.modalClose?.addEventListener("click", () => {
      this.statusModalInstance.hide();
    });

    // 状态模态框底部关闭按钮事件
    this.statusModalFooterClose?.addEventListener("click", () => {
      this.statusModalInstance.hide();
    });

    // 详情模态框关闭按钮事件
    this.detailModalClose?.addEventListener("click", () => {
      this.detailModalInstance.hide();
    });

    // 详情模态框底部关闭按钮事件
    this.detailModalFooterClose?.addEventListener("click", () => {
      this.detailModalInstance.hide();
    });

    // 状态表单提交事件
    this.statusForm?.addEventListener("submit", async (e) => {
      e.preventDefault();
      const id = this.applicationId.value;
      const status = this.statusSelect.value;

      try {
        await jobApplicationService.updateApplicationStatus(id, status);
        this.statusModalInstance.hide();
        this._loadData();
      } catch (error) {
        console.error("Error updating application status:", error);
        alert("更新投简状态失败：" + error.message);
      }
    });
  }

  _resetBatchDeleteButton() {
    this.batchDeleteBtn.disabled = true;
    this.batchDeleteBtn.innerHTML = `<i class="fas fa-trash"></i> 批量删除`;
  }

  _updateBatchDeleteButton() {
    const selectedCount = document.querySelectorAll(
      ".application-checkbox:checked"
    ).length;
    this.batchDeleteBtn.disabled = selectedCount === 0;
    if (selectedCount > 0) {
      this.batchDeleteBtn.innerHTML = `<i class="fas fa-trash"></i> 批量删除(${selectedCount})`;
    } else {
      this.batchDeleteBtn.innerHTML = `<i class="fas fa-trash"></i> 批量删除`;
    }
  }

  _addBackButton() {
    // 如果返回按钮已经存在，先移除它
    const existingBackButton =
      this.searchBtn.parentNode.querySelector(".btn-secondary");
    if (existingBackButton) {
      existingBackButton.remove();
    }

    // 添加返回按钮
    const backButton = document.createElement("button");
    backButton.className = "btn btn-secondary btn-sm ml-2";
    backButton.innerHTML = '<i class="fas fa-arrow-left"></i> 返回列表';
    backButton.onclick = () => {
      this._loadData();
      backButton.remove();
    };

    this.searchBtn.parentNode.insertBefore(
      backButton,
      this.searchBtn.nextSibling
    );
  }

  _showError(message) {
    this.applicationTableBody.innerHTML = `
      <tr><td colspan="10" class="text-center text-danger">${message}</td></tr>
    `;
    this._addBackButton();
  }

  _hidePagination() {
    this.pagination.classList.add("d-none");
  }

  _showPagination() {
    this.pagination.classList.remove("d-none");
  }

  async _showStatusModal(id) {
    try {
      const application = await jobApplicationService.getJobApplication(id);
      this.applicationId.value = id;
      this.statusSelect.value = application.applicationStatus || "待处理";
      this.statusModalInstance.show();
    } catch (error) {
      console.error("Error showing status modal:", error);
      alert("加载投简信息失败：" + error.message);
    }
  }

  async _showDetailModal(id) {
    try {
      const application = await jobApplicationService.getJobApplication(id);
      document.getElementById("detailId").textContent = application.id;
      document.getElementById("detailCompanyName").textContent =
        application.companyName || "-";
      document.getElementById("detailJobTitle").textContent =
        application.jobTitle || "-";
      document.getElementById("detailJobType").textContent =
        application.jobType || "-";
      document.getElementById("detailContactPhone").textContent =
        application.contactPhone || "-";
      document.getElementById("detailSeekerName").textContent =
        application.seekerName || "-";
      document.getElementById("detailSeekerPhone").textContent =
        application.seekerPhone || "-";
      document.getElementById("detailSeekerEmail").textContent =
        application.seekerEmail || "-";
      document.getElementById("detailApplicationDate").textContent =
        application.applicationDate || "-";
      document.getElementById("detailStatus").textContent =
        application.applicationStatus || "-";
      this.detailModalInstance.show();
    } catch (error) {
      console.error("Error showing detail modal:", error);
      alert("加载投简详情失败：" + error.message);
    }
  }
}
